package cn.itsource.org.service.impl;

import cn.itsource.basic.util.PageList;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
// 一般来说，在一个类中，查询的方法个数远远要大于增删改的个数，设置类级别事务为只读事务，
//里面所有的方法都继承这种事务，增删改覆盖写事务
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    //@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Transactional
    @Override
    public void add(Department department) {

        departmentMapper.save(department);
//        int i = 1/0;
    }

    @Transactional
    @Override
    public void delete(Long id) {

        departmentMapper.remove(id);
    }

    @Transactional
    @Override
    public void update(Department department) {

        departmentMapper.update(department);
    }

    @Override
    public Department getById(Long id) {
        return departmentMapper.loadById(id);
    }

    @Override
    public List<Department> getAll() {
        return departmentMapper.loadAll();
    }

    @Override
    public PageList<Department> queryPage(DepartmentQuery departmentQuery) {
        //封装PageList需要两个数据 total+datas
        //方案1：一条SQL直接返回PageList 不可行
        //方案2： 发两条sql，一条查询总数，一条查询数据
        long total = departmentMapper.queryCount(departmentQuery);
        if (total==0)
            return new PageList<>(); //{total:0，datas:[]}
        else {
            List<Department> datas = departmentMapper.queryData(departmentQuery);
            return new PageList<>(total,datas);
        }
    }
}
